<template>
  <div class="update-gender">
    <van-picker
      title="性别"
      show-toolbar
      :columns="columns"
      @confirm="onConfirm"
      @cancel="$emit('close')"
      @change="onPickerChange"
      :default-index="value"
    />
  </div>
</template>

<script>
import { updateUserprofile } from "@/api/user";
export default {
  name: "UpdateGender",
  props: {
    value: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      columns: ["男", "女"],
      localGender: this.value,
    };
  },
  methods: {
    // 监听变化
    onPickerChange(picker, value, index) {
      this.localGender = index;
    },
    async onConfirm() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true, // 禁止背景点击
        duration: 0, // 持续展示
      });
      try {
        updateUserprofile({
          gender: this.localGender,
        });
        this.$toast.success("更改性别成功");
        // 传给父级,关闭弹层
        this.$emit("close");
        // 传给父级,更改数据
        this.$emit("input", this.localGender);
      } catch (error) {
        this.$toast("修改性别失败");
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang="less"></style>
